<template>
    <div class="header-left">
        <div v-for="(item, index) in breadText" :key="index" class="header-bread">
            <p v-if="index === breadText.length - 1 || !item.path">{{ item.name }}</p>
            <p v-else class="canJump" @click="jumpBread(item)">{{ item.name }}</p>
            <p class="el-icon-arrow-right" v-if="index !== breadText.length - 1"></p>
        </div>
    </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
    data () {
        return {
            breadText: [],
            routeObj: {}
        }
    },

    computed: {
        ...mapState({
            'sideBarList': state => state.sideBar.sideBarList
        })
    },

    created () {
        this.sideBarList.forEach(item => {
            this.findChildren(item, [])
        })
        this.getBreadText(this.$route.path)
    },

    watch: {
        '$route.path': {
            handler (val) {
                this.getBreadText(val)
            },
            immediate: true
        }
    },

    methods: {
        // 获取路由链
        findChildren (item, list) {
            if (item.childrens) {
                let cItem = JSON.parse(JSON.stringify(item))
                if (cItem.childrens) {
                    cItem._parent = true
                    delete cItem.childrens
                }
                // 关键 list 添加当条数据
                list.push(cItem)
                item.childrens.forEach(_item => {
                    this.findChildren(_item, [...list])
                })
            } else {
                // 关键 list 添加当条数据
                list.push(item)
                this.routeObj[item.path] = list
            }
            // 如果有路由就添加到路由链当中
            if (item.path) {
                this.routeObj[item.path] = list
            }
        },

        // 路由跳转
        jumpBread (item) {
            this.$router.push({ path: item.path })
        },

        // 获取当前路由链
        getBreadText (path) {
            if (this.routeObj[path]) {
                this.breadText = [...this.routeObj[path]]
                try {
                    let parentList = this.breadText.filter((item) => item._parent)
                    let _path = parentList[parentList.length - 1].path || this.breadText[this.breadText.length - 1].path
                    this.$emit('change', _path)
                } catch (error) {
                }
            } else {
                this.breadText = []
            }
        }
    }
}
</script>

<style scoped lang="scss">
    .header-bread {
        display: flex;
        align-items: center;
    }
    .canJump {
        &:hover {
            color: #66b1ff;
            cursor: pointer;
        }
    }
</style>
